﻿using System;
using System.Collections.Generic;
using System.Text;

namespace XMK.Utils
{
    /// <summary>
    /// 日期处理类
    /// </summary>
    public static class DateHelper
    {
        /// <summary>
        /// 日期格式yyyy-MM-dd HH24:mi:ss
        /// </summary>
        public static readonly string FORMAT_yyyy_MM_dd_HH_mm_ss_fff = "yyyy-MM-dd HH:mm:ss:fff";
        public static readonly string FORMAT_yyyy_MM_dd = "yyyy-MM-dd";

        /// <summary>
        /// 从数据库取得的日期转换成字符串，格式：yyyy-MM-dd
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        public static string ToStr(object o)
        {
            return ToStr(o, FORMAT_yyyy_MM_dd);
        }
        /// <summary>
        /// 从数据库取得的日期转换成字符串，格式：yyyy-MM-dd HH:mm:ss:fff
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        public static string ToStrL(object o)
        {
            return ToStr(o, FORMAT_yyyy_MM_dd_HH_mm_ss_fff);
        }

        public static string ToStr(object o, string format)
        {
            if (o == null || o == DBNull.Value || string.IsNullOrEmpty(o.ToString()))
                return string.Empty;
            DateTime dt = DateTime.Parse(o.ToString());
            return dt.ToString(format);
        }

        /// <summary>
        /// 将日期转换成字符串格式
        /// </summary>
        /// <param name="date"></param>
        /// <param name="format"></param>
        /// <returns></returns>
        public static string ConvertString(DateTime date, string format)
        {
            return date.ToString(format);
        }
        /// <summary>
        /// 取得时间间隔，精确小数后4位
        /// </summary>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <returns></returns>
        public static string GetTimeSpanString(DateTime startTime,DateTime endTime)
        {        
            TimeSpan t = endTime.Subtract(startTime);
            return Math.Round(t.TotalMilliseconds, 0).ToString();
        }
        /// <summary>
        /// 取得与现在时间的时间间隔，精确小数后4位,
        /// </summary>
        /// <param name="startTime"></param>
        /// <returns></returns>
        public static string GetTimeSpanString(DateTime startTime)
        {
            return GetTimeSpanString(startTime, DateTime.Now);
        }
    }
}
